import {
  Http
} from '../../utils/http'
import {
  Tv
} from '../../model/Tv'
import {
  config
} from "../../config/config"
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';


Page({

  data: {
    tvId: '',
    tvName: undefined,
    videoUrl: [],
    result: [],
    show: true,
    tvList: [],
    videoHttp: '',
    uploadFileHttps:undefined,
    series_no: undefined,
    videoList_show: false,
    deletebtn: Number,
    tvClass: undefined,

    groupDetail: [],
    fileList: [],
    imgUrl:undefined,
    option1: [],
    value1: 0,
    group_id:0,
  },

  //生命周期函数--监听页面加载
  onLoad: async function (options) {
    this.setData({
      tvId: options.tvListId,
      videoHttp: config.apiBaseUrl,
      tvClass: options.tvClass,
      uploadFileHttps:config.apiBaseUrl+'wechat/attachment/upload'
    })
  },

  //生命周期函数--监听页面显示
  onShow: async function () {
    let http = await Http.login();
    //判断是组还是盒子 if !=undefined为组
    if (this.data.tvClass != undefined && this.data.tvClass != '') {
      if (this.data.tvId == undefined) {
        console.log('tvId为undified');
      } else {
        this.get_video_group_detail()
      }
    } else {
      this.get_video_group_list()
      if (this.data.tvId == undefined) {
        console.log('tvId为undified');
        this.setData({
          videoList_show: true,
          deletebtn: 0,
          show: true
        })
      } else {
        let tv = await Tv.get_tvbox_detail(this.data.tvId);
        this.getTvDetail(tv)
        this.setData({
          videoList_show: false,
          deletebtn: 0,
          show: true
        })
      }
    }
  },

  //获取到视频组
  getTvDetail(tv) {
    if (tv.code == 0) {
      this.setData({
        series_no: tv.data.series_no,
        tvName: tv.data.name,
        value1:tv.data.group_id
      })
      if (tv.data.video_files != '') {
        this.setData({
          videoUrl: tv.data.video_files.split(',')
        })
      } else {
        this.setData({
          videoUrl: []
        })
      }
    } else {
      wx.showToast({
        title: tv.msg,
        icon:'error'
      })
    }
  },

  //点击添加视频按钮
  addVideoTap: function () {
    var that = this;
    if (this.data.deletebtn == 1) {
      const beforeClose = (action) => new Promise((resolve) => {
        setTimeout(() => {
          if (action === 'confirm') {
            this.submitVideoTap();
            resolve(true);

          } else {
            // 拦截取消操作
            wx.showLoading({
              title: '加载中',
            })
            that.onShow();
            wx.hideLoading();
            resolve(true);

          }
        }, 1000);
      });

      Dialog.confirm({
        title: '警告',
        message: '删除操作是否提交',
        beforeClose
      });
    } else {
      this.wxApiSubmitVideo()
    }

  },

  //上传视频wxApi接口
  wxApiSubmitVideo() {
    var that = this;
    //选择视频
    wx.chooseVideo({
      compressed: true,
      sourceType: ['album', 'camera'], //视频选择的来源
      maxDuration: 15, //拍摄视频最长拍摄时间，单位秒
      camera: 'back', //默认拉起的是前置或者后置摄像头。部分 Android 手机下由于系统 ROM 不支持无法生效
      success(res) {
        wx.showLoading({
          title: '加载中...',
          icon: 'loading',
        });

        //上传视频
        wx.uploadFile({
          compressed: true,
          url: that.data.uploadFileHttps, //开发者服务器的 url
          filePath: res.tempFilePath, //要上传文件资源的路径 String类型！！！
          name: 'file', //文件对应的 key ,(后台接口规定的关于图片的请求参数)
          header: {
            'content-type': 'multipart/form-data'
          },
          //设置请求的 header
          formData: {

          }, //HTTP 请求中其他额外的参数
          success: function (res) {
            //上传成功后隐藏加载框
            wx.hideLoading();
            if (res != '' && res != undefined)
              var data = JSON.parse(res.data)
            if (data.code == 0) {
              var arr = that.data.videoUrl;
              arr.push([data.data.url])
              that.setData({
                videoUrl: arr
              })
            } else {
              console.log("code码为非0");
              console.log(data);
            }
          },
          fail: function (res) {
            console.log('uploadFile失败:');
            wx.showToast({
              title: '上传失败',
              icon: 'error'
            }, 500)
            console.log(res);
            wx.hideLoading();
          }
        })
      },
    })
  },

  //点击删除视频按钮
  removeVideoTap: function () {
    this.setData({
      show: !this.data.show
    })
  },

  //点击删除视频小按钮
  onChange(event) {
    this.setData({
      result: event.detail,
    });
    if (this.data.videoUrl != '') {
      for (let i = 0; i < this.data.videoUrl.length; i++) {
        if (this.data.videoUrl[i] == this.data.result[i]) {
          let a = this.data.videoUrl
          let urls = a[i]
          this.del(urls);
          a[i] = ""
          this.setData({
            videoUrl: a,
          })
        }
        for (let a = 0; a < i; a++) {
          if (this.data.videoUrl[i] == this.data.result[a]) {
            let a = this.data.videoUrl
            let urls = a[i]
            this.del(urls);
            a[i] = ""
            this.setData({
              videoUrl: a,
            })
          }
        }
      }
    } else {
      wx.showToast({
        title: '没有任何视频',
        icon: 'error'
      })
    }
    this.setData({
      result: ''
    });
  },

  //视频删除
  del: async function (urls) {
    this.setData({
      deletebtn: 1
    })
    var that = this;
    if (urls != '') {
      let tvdel = await Tv.get_del(urls);
      if (tvdel.code == 0) {
        console.log(tvdel.msg);
        for (let i = 0; i < this.data.videoUrl.length; i++) {
          if (this.data.videoUrl[i] == "") {
            let a = this.data.videoUrl
            a.splice(i, 1)
            this.setData({
              videoUrl: a
            })
          }
        }
      } else {
        console.log(tvdel.msg);
      }
    }
  },

  //点击提交按钮
  submitVideoTap: async function () {
    var that = this;
    //如果tvClass有值就为组的事件
    if (this.data.tvClass == 0) {
      //如果tvId为undefined则表现在为创建组
      if (this.data.tvId == undefined || this.data.tvId == '') {
        if (this.data.tvName == undefined) {
          wx.showToast({
            title: '名称不能为空',
            icon: 'error'
          })
        } else {
          const beforeClose = (action) => new Promise((resolve) => {
            setTimeout(() => {
              if (action === 'confirm') {
                this.add_video_group()
                resolve(true);
              } else {
                // 拦截取消操作
                resolve(true);
              }
            }, 1000);
          });

          Dialog.confirm({
            title: '提交',
            message: '确认提交吗？',
            beforeClose
          });
        }
      } else {
        if (this.data.tvName == undefined) {
          wx.showToast({
            title: '名称不能为空',
            icon: 'error'
          })
        } else {
          const beforeClose = (action) => new Promise((resolve) => {
            setTimeout(() => {
              if (action === 'confirm') {
                this.edit_video_group()
                resolve(true);
              } else {
                // 拦截取消操作
                resolve(true);
              }
            }, 1000);
          });

          Dialog.confirm({
            title: '提交',
            message: '确认提交吗？',
            beforeClose
          });
        }
      }
    } else {
      //如果tvId为undefined则表现在为创建Tv盒子
      if (this.data.tvId == undefined || this.data.tvId == '') {
        if (this.data.tvName == '' || this.data.tvName == undefined) {
          wx.showToast({
            title: '名称不能为空',
            icon: 'error'
          })
        } else if (this.data.videoUrl == '' || this.data.videoUrl == undefined) {
          wx.showToast({
            title: '视频组不能为空',
            icon: 'error'
          })
        } else {
          const beforeClose = (action) => new Promise((resolve) => {
            setTimeout(() => {
              if (action === 'confirm') {
                that.saveTvbox();
                resolve(true);
                setTimeout(() => {
                  function a() {
                    setTimeout(() => {
                      wx.showToast({
                        title: '增加成功',
                        icon: 'success'
                      })

                    }, 500);
                  }
                  wx.navigateBack()
                }, 1000);
              } else {
                // 拦截取消操作
                resolve(true);
              }
            }, 1000);
          });

          Dialog.confirm({
            title: '提交',
            message: '确认提交吗？',
            beforeClose
          });
        }
      } else {
        const beforeClose = (action) => new Promise((resolve) => {
          setTimeout(() => {
            if (action === 'confirm') {
              that.edit();
              resolve(true);
              setTimeout(() => {
                wx.showToast({
                  title: '修改成功',
                  icon: 'success'
                })
                that.onShow()
              }, 1000);
            } else {
              // 拦截取消操作
              resolve(true);
            }
          }, 1000);
        });

        Dialog.confirm({
          title: '提交',
          message: '确认提交吗？',
          beforeClose
        });
      }
    }
  },

  //修改接口实现
  edit: async function () {
    //TV盒子列表 修改
    console.log(this.data.group_id);
    let tvListUpdate = await Tv.get_edit_tvbox_detail(this.data.tvId, this.data.tvName, this.data.videoUrl.toString(), this.data.group_id,this.data.series_no,);
    if (tvListUpdate.code == 0) {
      console.log(tvListUpdate.msg);
      wx.showLoading({
        title: '加载中',
      })
      this.onShow()
      wx.hideLoading()
    } else {
      console.log(tvListUpdate.msg);
    }
  },

  //Tv盒子增加接口实现
  saveTvbox: async function () {
    let saveTvbox = await Tv.save_tvbox_detail(this.data.tvName, this.data.videoUrl.toString());
    if (saveTvbox.code == 0) {
      console.log(saveTvbox);
    } else {
      console.log(saveTvbox.msg);
    }
  },

  //组 - 查询接口实现
  async get_video_group_detail() {
    let tv = await Tv.get_video_group_detail(this.data.tvId);
    if (tv.code == 0) {
      
      this.setData({
        groupDetail: tv.data,
        tvName: tv.data.name,
      })
      if (tv.data.video_files != '') {
        this.setData({
          videoUrl: tv.data.video_files.split(',')
        })
      } else {
        this.setData({
          videoUrl: []
        })
      }
    } else {
      console.log(tv.msg);
    }
  },

  //图片上传
  afterRead(event) {
    let that = this
    const {
      file
    } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      url: that.data.uploadFileHttps, // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: 'file',
      formData: {
        user: 'test'
      },
      success(res) {
        // 上传完成需要更新 fileList
        const {
          fileList = []
        } = that.data;
        fileList.push({
          ...file,
          url: res.data
        });
        that.setData({
          fileList,
          imgUrl:JSON.parse(that.data.fileList[0].url).data.url
        });
      },
    });
  },

  //组 - 增加接口实现
  async add_video_group() {
    let tv = await Tv.add_video_group(this.data.tvName);
    if (tv.code == 0) {
      wx.showToast({
        title: tv.msg,
        icon: "success"
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1000);
    } else {
      alert.log(tv.msg);
    }
  },

  //组 - 修改接口实现
  async edit_video_group() {
    if(this.data.imgUrl==undefined){
      this.setData({imgUrl:this.data.groupDetail.icon_avatar})
    }
    let that = this;
    let tv = await Tv.edit_video_group(this.data.groupDetail.id, this.data.tvName, this.data.imgUrl, this.data.videoUrl.toString())
    this.setData({fileList:[]})
    if (tv.code == 0) {
      wx.showToast({
        title: '修改成功',
        icon: 'success'
      })
      setTimeout(() => {
        that.get_video_group_detail();
      }, 1000);
    }
  },

  //组 - 列表 查询接口实现
  async get_video_group_list(){
    let tv = await Tv.get_video_group_list()
    if(tv.code==0){
      let s=[]
      for(let i=0;i<tv.data.length;i++){
        s.push({text:tv.data[i].name,value:tv.data[i].id})
      }
      this.setData({
        option1:s
      })
    }else{
      wx.showToast({
        title: tv.msg,
        icon:'error'
      })
    }
  },

  //下拉框改变
  menu(e){
    this.setData({group_id:e.detail})
  }

})